<template>
  <div class="the-page" v-if="blockDetail">

    <div class="panel-search">
      <el-form ref="form" label-width="100px" label-position="left">
        <el-form-item label="区块编码：">
          <el-tag type="info">{{blockDetail.id}}</el-tag>
        </el-form-item>
        <el-form-item label="区块名称：">
          <el-tag type="info">{{blockDetail.name}}</el-tag>
        </el-form-item>
        <el-form-item label="key：">
          <el-tag type="info">{{blockDetail.keyName}}</el-tag>
        </el-form-item>
        <el-form-item label="class名称：">
          <el-tag type="info">{{blockDetail.pageClass.title}}</el-tag>
        </el-form-item>
        <el-form-item label="是为列表：">
          <el-tag type="info">{{blockDetail.isList?'是':'否'}}</el-tag>
        </el-form-item>
      </el-form>

    </div>

    <div class="panel-table">
      <div class="table-head">
        <span>数据列表</span>
        <div>
          <el-button type="primary" icon="icon-plus" :disabled="blockDetail.isList==0" @click.stop="addItem()">新增</el-button>
          <el-button type="primary" icon="icon-folder-checked" @click.stop="confirmHandle()">保存</el-button>
        </div>
      </div>
      <el-card class="box-card" style="margin-top:8px;" v-for="(item,index) in contents" :key="index">
        <template #header>
          <div class="clearfix">
            <span>{{index+1}}</span>
            <el-button size="small" @click="deleteItemHandle(item,index)" type="danger">删除</el-button>
          </div>
        </template>
        <el-form ref="itemForm" label-width="100px">
          <el-form-item v-for="(item2,index2) in item" :key="index2" :label="item2.label" required>
            <div style="color:#a4a4a4;" v-if="item2.hint">{{item2.hint}}</div>

            <el-input v-model="item2.value" v-if="item2.type == 'input'" :disabled="item2.disable == 'true'" autocomplete="off" :show-word-limit="!!item2.maxLength" :maxlength="item2.maxLength"></el-input>

            <el-date-picker v-else-if="item2.type == 'date'" v-model="item2.value" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="选择日期时间" align="right">
            </el-date-picker>

            <el-switch v-else-if="item2.type == 'switch'" v-model="item2.value" active-value="1" inactive-value="0">
            </el-switch>

            <el-switch v-else-if="item2.type == 'onlySwitch'" v-model="item2.value" active-value="1" inactive-value="0" :disabled="item2.value==='1'" @change="(status)=>{status==='1'?checkOtherSwtch(index,index2):null}">
            </el-switch>

            <template v-else-if="item2.type == 'select'">
              <div v-for="(itm,index3) in item2.option" style="margin-bottom: 10px" :key="index3">
                <el-select v-model="itm.id" placeholder="请选择">
                  <el-option v-for="(opt,index4) in item2.value" :key="opt" :label="opt" :value="index4">
                  </el-option>
                </el-select>
                <el-input v-model="itm.input" style="width:250px" plain></el-input>
                <el-button type="danger" plain @click="deleteOption(index,index2,index3)" :disabled="item2.option.length == 1">删除</el-button>
              </div>
              <el-button type="primary" v-if="item2.option.length < 5" @click="addOption(index,index2)">增加</el-button>
            </template>
            
            <!-- 填写图片文件地址，附图片上传功能 -->
            <inputUpload v-else-if="item2.type == 'imageInput'" v-model="item2.value" :disabled="item2.disable == 'true'"></inputUpload>

          </el-form-item>
        </el-form>
      </el-card>

    </div>

  </div>
</template>

<script>
// import Pagination from "@/components/Pagination";
import { getBlockOne, createItems } from "@/api/config";
import { ElNotification, ElMessageBox,ElMessage } from "element-plus";
import inputUpload from "@/components/Upload/inputUpload.vue";
export default {
  name: "universalBlockItems",
  components: {
    // Pagination,
    inputUpload,
  },
  data() {
    return {
      tempRoute: {},
      blockDetail: null,
      contents: [],
      classTypes: [],
      itemForms: [],
    };
  },
  created() {
    this.getblockDetail();

    this.tempRoute = Object.assign({}, this.$route);
  },
  methods: {
    getblockDetail(theId) {
      const id = theId || this.$route.params?.id;
      if(id === undefined)return;
      getBlockOne(id).then((res) => {
        this.contents = [];
        this.blockDetail = res.data;
        this.classTypes = JSON.parse(res.data.pageClass.template);
        // console.log(342342, this.classTypes)
        this.filterItems();
      });
    },
    filterItems() {
      if (this.blockDetail.content) {
        //编辑
        let content = this.blockDetail.isList
          ? JSON.parse(this.blockDetail.content)
          : new Array(JSON.parse(this.blockDetail.content));
        content.map(() => {
          this.addItem();
        });
        this.contents.map((value, index) => {
          value.map((value2) => {
            if (value2.type == "select") {
              value2.option = content[index][value2.key];
            } else {
              value2.value = content[index][value2.key];
            }
          });
        });
        console.log(3333, this.contents);
      } else {
        //新增
        this.addItem();
      }
    },
    addItem() {
      let copy = JSON.parse(JSON.stringify(this.classTypes));
      this.contents.push(copy);
    },
    formatParams() {
      let result = [];
      for (let i = 0; i < this.contents.length; i++) {
        const item = this.contents[i];
        result.push({});
        for (let k = 0; k < item.length; k++) {
          if (item[k].value) {
            if (item[k].type == "select") {
              result[i][item[k].key] = item[k].option;
            } else {
              result[i][item[k].key] = item[k].value;
            }
          } else {
            ElNotification({
              title: "提示",
              message: "请完善数据",
              type: "warning",
              duration: 2000,
            });
            result = [];
            return false;
          }
        }
      }
      return result;
    },
    confirmHandle() {
      let items = JSON.parse(JSON.stringify(this.formatParams()));
      if (!items) return;
      let data = {
        id: this.blockDetail.id,
        name: this.blockDetail.name,
        content:
          this.blockDetail.isList == 1
            ? JSON.stringify(items)
            : JSON.stringify(items[0]),
      };
      console.log(data.content);
      createItems(data).then(() => {
        ElNotification({
          title: "成功",
          message: "内容更新成功",
          type: "success",
          duration: 2000,
        });
        this.$store.dispatch("tagsView/delView", this.tempRoute).then(() => {
          this.$router.replace({
            path: `/config/list/blocks/${this.blockDetail.pageId}`,
          });
        });
      });
    },
    deleteItemHandle(item, index) {
      // 判断是否存在 onlySwitch（开启的onlySwitch不能删除）
      for(let prop of item||[]){
        if(prop.type === "onlySwitch" && prop.value==="1"){
          ElMessage.warning("无法删除开启的项！");
          return;
        }
      }
      ElMessageBox.confirm("是否删除该条?", "提示", {
        type: "warning",
      }).then(() => {
        this.contents.splice(index, 1);
      });
    },
    // 删除select的一项
    deleteOption(index, index2, index3) {
      this.contents[index][index2].option.splice(index3, 1);
    },
    // 想slect里面增加一项
    addOption(index, index2) {
      this.contents[index][index2].option.push({
        id: "",
        input: "",
      });
    },
    // onlySwitch，确保至多有一个开关处于开启状态
    checkOtherSwtch(index,index2){
      let len =  this.contents?.length || 0;
      for(let i=0;i<len;i++){
        let item = this.contents[i]||[];
        if(i!==index){
          if(item[index2].value === "1"){
            item[index2].value = "0";
            break;
          }
        }
      }

    }
  },
  beforeRouteUpdate(to,from,next){
    // 从相同路由进入（不同参数），如/a/b/1 => /a/b/2
    this.getblockDetail(to.params.id);
    next();
  }
};
</script>

<style scope lang="scss">
@import "@/styles/tablePage.scss";
.panel-search{
  padding: 12px 12px 4px 12px;
}
.clearfix{
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.el-card__body{
  padding: 18px 18px 0 18px;
}
</style>
